<style>
 @import 'bifen.less';
</style>

<template>
<div style="padding:20px;">
    <div class="fixed-bar title">
    	选择比分
		<div v-if="!isPreparePrint" style="float:right;">
			<Button size="large" icon="ios-game-controller-b-outline" type="dashed" onclick="window.open('http://saishi.zgzcw.com/soccer/cup/103')">赛事中心</Button>
			<Button size="large" icon="md-calendar" type="dashed" onclick="window.open('/Home/details')">历史记录</Button>		
		</div>
	</div>

    <div class="mylayout">
		<!--添加比赛-->
      	<div v-if="openTableFlag == false">
			<div class="fixed-bar" style="top:60px;padding:10px;background-color:#f8f8f8;border-bottom:1px solid #ddd">
				<Row>
					<Col :sm="{ span: 24, offset: 0 }" :md="{ span: 16, offset: 4 }">
						<Button size="large" type="primary" icon="md-add" @click="addGame()">添加场次({{ model.games.length }})</Button>
						<Button size="large" type="error" icon="ios-nuclear-outline" @click="clearGames()">清空</Button>
						<InputNumber :min="0" :step="100" style="float:right;width:200px;" size="large" v-model="model.total_bet" placeholder="请输入总赌注,单位元" number/>
					</Col>
				</Row>
			</div>
			<Row style="padding-top:100px;padding-bottom:60px;">
				<Col :sm="{ span: 24, offset: 0 }" :md="{ span: 16, offset: 4 }">
					<Card v-for="(item, index) in model.games" :key="index" style="margin-top: 20px" :bordered="true">
						<p slot="title" style="overflow:visible;">
							<span style="font-size: 18px;"> 编号{{index+1}}</span>
							<Button icon="md-close" @click="deleteGame(index)" type="error" style="float:right;">移除</Button>
						</p>
						<Row>
							<Col span="10">
								<Input class="large-input" v-model="item.home_team_name" placeholder="主队"/>
							</Col>
							<Col span="4" style="text-align: center;font-size: 18px;">
								VS
							</Col>
							<Col span="10">
								<Input class="large-input" v-model="item.visiting_team_name" placeholder="客队"/>
							</Col>
						</Row>
						<Button @click="selectScore(index)" type="primary" ghost style="width: 100%;font-size: 18px;margin-top:10px;">
							{{getGameButtonName(item) }}
						</Button>
					</Card>
				</Col>
			</Row>
			<div style="position:fixed;left:0;bottom:0;background-color:#fff;padding:10px;border-top:1px solid #eee;width:100%;text-align:center;">
				<Button style="font-size:1.7em;" icon="ios-paper" type="primary" @click="handleGenerateReport()">生成报表</Button>
			</div>
		</div>

		<!--报表显示-->
		<div id="mychart" v-if="openTableFlag == true">
			<div id="buttons" class="fixed-bar" style="top:60px;background-color:rgba(255,255,255,0.9);border-bottom:1px solid #ddd">
				<Row>
					<Col :sm="{ span: 24, offset: 0 }" :md="{ span: 20, offset: 2 }">
						<!--按钮组-->
						<ButtonGroup size="large" style="margin: 10px;float:right;">
							<Button v-if="!isPreparePrint" icon="ios-search" @click="handleShowSearchPanel"></Button>
							<Button :icon="isPreparePrint?'ios-apps':'ios-print'" @click="handleSwitchMode" :title="isPreparePrint?'切换到操作模式':'切换到打印模式'"></Button>
						</ButtonGroup>
						<ButtonGroup size="large" style="margin: 10px;float:right;">
							<Button style="width:150px;" @click="openParamDetail = true">比赛场次：{{ model.games.length }}</Button>
							<Button style="width:150px;" type="dashed">总投资额：{{model.total_bet}}</Button>
							<Button style="width:150px;" type="dashed">记录总数：{{model.results.length}}</Button>
						</ButtonGroup>
						<ButtonGroup size="large" style="margin: 10px">
							<Button v-if="!isPreparePrint" style="width:100px;" icon="ios-arrow-back" type="primary" @click="backScore()">返回</Button>
							<Button v-if="isPreparePrint" style="width:100px;" icon="ios-print" type="primary" @click="print()">打印</Button>
							<Button v-if="!isPreparePrint" style="width:100px;" icon="ios-cloud-upload" type="primary" @click="showSaveModal()">保存</Button>
						</ButtonGroup>
						<ButtonGroup v-if="!isPreparePrint" size="large" style="margin: 10px;">
							<Button style="width:100px;" type="primary" @click="calcByWeight()">权重分配</Button>
							<Button style="width:100px;" type="primary" @click="calcByAvg()">平均分配</Button>
						</ButtonGroup>
						<!--查找面板-->
						<div v-if="!isPreparePrint && showSearchPanel" style="text-align:center;margin-top:5px;border-top:1px solid #f0f0f0;padding-top:5px;width:100%;float:right;">
							<div v-for="(game, index) in model.games" style="display:inline-block;border:1px solid #eee;margin-right:5px;padding:2px 5px;" :key="index">
								<span>{{ search.games[index].name }}</span>
								<Select v-model="search.games[index].score" style="width:75px;text-align:center;">
									<Option v-for="(score, key) in game.scores" :value="key" :key="key">{{ key }}</Option>
								</Select>
							</div>
							<Button style="width:100px;margin:2px 5px;" icon="ios-search" type="primary" @click="handleSearchResult">查找</Button>
						</div>
					</Col>
				</Row>
			</div>
			<!--列出所有的显示结果-->
			<Row :style="{ 'padding-top': top_height + 'px', 'text-align': 'center' }">
				<Col :sm="{ span: 24, offset: 0 }" :md="{ span: 16, offset: 4 }">
					<Card v-for="(item, index) in model.results" :id="index" :class="{'selected-item':search.selected_index==index}" style="margin-top:10px;">
						<p slot="title">
							<span style="font-size:18px;">编号{{index+1}}</span>
						</p>
						<!--表格-->
						<Row style="text-align:center;">
							<Col span="6" class="result-cell"><strong>场次</strong></Col>
							<Col span="6" class="result-cell"><strong>比分</strong></Col>
							<Col span="6" class="result-cell"><strong>权重(%)</strong></Col>
							<Col span="6" class="result-cell"><strong>赔率</strong></Col>
							<Row v-for="game in item.games">
								<Col span="6" class="result-cell">{{ game.name }}</Col>
								<Col span="6" class="result-cell">{{ game.score }}</Col>
								<Col span="6" class="result-cell">{{ game.weight }}</Col>
								<Col span="6" class="result-cell">{{ game.odds }}</Col>
							</Row>
						</Row>
						<!--汇总-->
						<Row>
							<Col span="3" class="result-cell">
								<span style=" ">总计</span>
							</Col>
							<Col span="7" class="result-cell">
								<span style=" ">总赔率&nbsp;&nbsp;&nbsp;{{item.total_odds }}</span>
							</Col>
							<Col span="7" class="result-cell">
								<span style=" ">总权重&nbsp;&nbsp;&nbsp;{{item.total_weight.toFixed(8)}}</span>
							</Col>
							<Col span="7" class="result-cell">
								<span style=" ">总赔率* 总权重&nbsp;&nbsp;&nbsp;{{item.total_weight_times_odds.toFixed(2) }}</span>
							</Col>
						</Row>
						<!--收支-->
						<Row>
							<Col span="3" class="result-cell">
								<span style="width: 100%;">收支</span>
							</Col>
							<Col span="7" class="result-cell">
								<span style="">投资金额</span>
								<span v-if="isPreparePrint">{{ item.total_amount }}</span>
								<InputNumber v-if="!isPreparePrint" v-model="item.total_amount" :min="0" :step="100" placeholder="投资金额" width="100%"/>
							</Col>
							<Col span="7" class="result-cell">
								<span style="width: 100%"> 回报金额&nbsp;&nbsp;&nbsp;{{item.return_amount }}</span>
							</Col>
							<Col span="7" class="result-cell">
								<Button v-if="!isPreparePrint" type="primary" icon="ios-brush" @click="adjustAmount(item)" style="width: 80%">调整</Button>
							</Col>
						</Row>
					</Card>
				</Col>
			</Row>
      	</div>

		<select-score ref="select-score"></select-score>

		<Modal v-model="openInputBetFlag" title="请输入总赌注">
			<InputNumber v-model="model.total_bet" :min="0" :step="100" placeholder="请输入总赌注" autofocus style="width:100%" />
			<div slot="footer">
				<Button type="primary" size="large" long @click="handleGenerateReport">确定</Button>
			</div>
		</Modal>
		<!--参数面板-->
		<Modal v-model="openParamDetail" title="比赛场次" width="75">
			<Row style="text-align:center;font-size:1.2em;">
				<Col span="8">比分</Col>
				<Col span="8">权重(%)</Col>
				<Col span="8">赔率</Col>
				<Row v-for="game in model.games">
					<Col span="24" style="background-color:#eee;padding:5px;">{{ getGameName(game) }}</Col>
					<Row v-for="(score, key) in game.scores" style="border-bottom:1px solid #eee;padding:5px;">
						<Col span="8">{{ key }}</Col>
						<Col span="8">{{ score.weight }}</Col>
						<Col span="8">{{ score.odds }}</Col>
					</Row>
				</Row>
			</Row>
		</Modal>
    </div>
</div>
</template>

<script>
import SelectScore from "./select-score.vue"

export default {
	name: 'Score',
	components: {
		SelectScore
	},
    data () {
		return {
			// 页面显示开关
			openInputBetFlag: false, // 输入比分页面
			isPreparePrint: false, // 是否准备打印，是的话会隐藏很多图标
			openTableFlag: false, // 是否显示报表
			openParamDetail: false, // 显示详细参数
			showSearchPanel: false, // 是否显示查找面板
			is_history: false, // 是否是查看的历史
			// 数据模型
			model: {
				total_bet: null,//总赌注
				games: [ // 所有比赛
					// { 
					// 	home_team_name: "", // 主队名称
					// 	visiting_team_name: "", // 客队名称
					// 	scores: { // 选择的比分
					// 		"1:0": { 
					// 			weight: 10, // 权重
					// 			odds: 0 // 赔率
					// 		} 
					// 	} 
					// }
				],
				results: [ // 报表生成结果
					// { 
					// 	total_odds: 0, // 总赔率
					// 	total_weight: 0, // 总权重
					// 	total_amount: 0, // 总金额
					// 	return_amount: 0, // 回报金额
					// 	total_weight_times_odds: 0, // 总权重 * 总赔率，为排序辅助变量
					// 	games: [
					// 		{
					// 			name: "", // 比赛名称
					// 			score: "", // 比赛比分
					// 			odds: 0, // 赔率
					// 			weight: 0 // 权重
					// 		}
					// 	] 
					// }
				] 
			},
			// 报表结果相关变量
			top_height: 0,
			search: { // 定位搜索相关
				games: [],
				selected_index: -1
			},
			save_remark: "", // 保存时的备注信息
		}
    },
    methods: {
		addGame() { // 添加比赛
			this.model.games.push({
				home_team_name: "", 
				visiting_team_name: "", 
				scores: {  }
			});
		},
		deleteGame(index) { // 删除比赛
			this.model.games.splice(index, 1);
		},
		clearGames(){ // 清空所有比赛
			this.model.games = [];
		},
		getGameButtonName(game) { // 比赛比分选择按钮显示文字
			var keys = Object.keys(game.scores);
			return keys.length ? keys.toString() : "请选择投注内容";
		},
		AlertTipModal(content, tag) { // 错误提示
			tag = tag || 'error'
			this.$Modal[tag]({
				title: "提示",
				content: content,
				width: 200
			});
		},
		selectScore(index){ // 选择比分
			this.$refs["select-score"].showModal(this.model.games[index]);
		},
		print(){ // 打印
			setTimeout(function () {
				return window.print();
			}, 3000);
		},
		getGameName(game) {
			return `${game.home_team_name} VS ${game.visiting_team_name}`;
		},
		doExchage(games, index, base){ // 将所有的比赛结果进行组合
			if(index >= games.length) return base;

			var base2 = [];
			var new_base = [];
			var game = games[index];
			var scores = game.scores;
			var game_name = this.getGameName(game);

			for(var k in scores) {
				base2.push({
					name: game_name,
					score: k,
					weight: scores[k].weight,
					odds: scores[k].odds
				});
			}

			for(var i = 0; i < base.length; i++) {
				for(var j = 0; j < base2.length; j++) {
					var temp = [];
					for(var k = 0; k < base[i].length; k++) {
						temp.push(base[i][k]);
					}
					temp.push(base2[j]);
					new_base.push(temp);
				}
			}

			return this.doExchage(games, index + 1, new_base);
		},
		backScore(){ // 返回
			this.openTableFlag = false;
		},
		handleGenerateReport(){
			this.openInputBetFlag = !this.generateReport();
		},
		generateReport() { // 生成报表
			if(!this.model.total_bet) {
				return false;
				//this.AlertTipModal("请输入总赌注");
			}
			this.search.games = this.model.games.reduce((total, elem) => {
				var game_name = this.getGameName(elem);
				total.push({
					name: game_name,
					score: ""
				});
				return total;
			}, []);
			this.createResults();
			this.calcByWeight();
			this.openTableFlag = true;
			return true;
		},
		createResults() { // 生成列举结果，但不计算金额
			if(this.model.games.length == 0) return;
			var model = this.model;
			var temp = [];

			var list = this.doExchage(model.games, 0, [[]]);
			for(var i = 0; i < list.length; i++) {
				var item = list[i];
				var total_weight = item.reduce((total, elem) => { return total * elem.weight * 0.01; }, 1);
				var total_odds = item.reduce((total, elem) => { return total * elem.odds; }, 1);
				temp.push({
					total_weight: total_weight,
					total_odds: total_odds,
					total_weight_times_odds: total_weight * total_odds,
					games: item
				});
			}

			// 排序
			temp.sort((a, b) => {
				if (a.total_weight_times_odds > b.total_weight_times_odds) {
					return -1;
				} else if (a.total_weight_times_odds < b.total_weight_times_odds) {
					return 1
				} else {
					return 0;
				}
			});

			model.results = temp;
		},
		calcByWeight() { // 按权重计算金额
			if(this.model.results.length == 0) return;
			var model = this.model;
			var temp = model.results;
			model.results = [];

			for(var i = 0; i < temp.length; i++) {
				var item = temp[i];
				item.total_amount = (model.total_bet * item.total_weight).toFixed(2);
				item.return_amount = (item.total_amount * item.total_odds).toFixed(2);
			}

			model.results = temp;
		},
		calcByAvg(){ // 平均分配金额
			if(this.model.results.length == 0) return;
			var model = this.model;
			var temp = model.results;
			model.results = [];

			var avg_amount = model.total_bet / temp.length;
			for(var i = 0; i < temp.length; i++) {
				var item = temp[i];
				item.total_amount = avg_amount.toFixed(2);
				item.return_amount = (item.total_amount * item.total_odds).toFixed(2);
			}

			model.results = temp;
		},
		adjustAmount(item){ // 调整单项金额
			item.return_amount = (item.total_amount * item.total_odds).toFixed(2);
			this.model.total_bet = this.model.results.reduce((total, item) => {
				return total + parseInt(item.total_amount);
			}, 0);
		},
		showSaveModal(){ // 显示保存窗口
			this.$Modal.confirm({
				title: "保存前请输入备注",
				render: (h) => {
					return h('Input', {
						props: {
							value: this.save_remark,
							autofocus: true,
							placeholder: '请输入备注'
						},
						on: {
							input: (val) => {
								this.save_remark = val;
							}
						}
					})
				},
				onOk: () => {
					this.save();
				}
			});
		},
		save(){ // 保存
			var temp = JSON.stringify({
				total_bet: this.model.total_bet,
				games: this.model.games
			});
			this.$http.post('/Home/AjaxPost', { json_data: temp, remark: this.save_remark }).then(response => {
				if(response.body.status == "200") {
					this.AlertTipModal(response.body.msg, "success");
				}else {
					this.AlertTipModal(response.body.msg);
				}
			
			});
		},
		handleSearchResult() { // 查找
			// 得到搜索的比赛键值对
			var kv1 = this.search.games.reduce((total, elem) => {
				if(elem.score != "") {
					total[elem.name] = elem.score;
				}
				return total;
			}, {});

			var index = this.model.results.findIndex(elem => {
				// 得到要当前要匹配的条目的比赛键值对
				var kv2 = elem.games.reduce((total, elem) => {
					total[elem.name] = elem.score;
					return total;
				}, {});

				// 将这个键值对kv1与搜索的键值对kv2进行比较
				for(var k in kv1) {
					if(kv1[k] != kv2[k]) {
						// 说明存在不匹配项，则该条目略过
						return false;
					}
				}
				return true;
			});
			this.search.selected_index = index == -1 ? 0 : index;
			document.getElementById(this.search.selected_index).scrollIntoView(false);
		},
		handleShowSearchPanel() {
			this.showSearchPanel = !this.showSearchPanel;
		},
		handleSwitchMode() {
			if(this.isPreparePrint) {
				//this.showSearchPanel = false;
				this.isPreparePrint = false;
			}else {
				this.isPreparePrint = true;
			}
		},
		refreshTopHeight() {
			var height = 0;
			var temp = setInterval(() => {
				var elem = document.getElementById("buttons");
				if(elem && elem.offsetHeight != height) {
					this.top_height = elem.offsetHeight + 50;
					// if(this.top_height > 50) {
					// 	clearInterval(temp);
					// }
				}
			}, 100);
			// $(window).resize(() => {
			// 	this.refreshTopHeight();
			// });
		}
	},
	created() {
		this.$http.post('/Home/GetInfo', { id: this.$route.query.id }).then(response => {
			if(response.body == "") return;
			this.model = JSON.parse(response.body);
			this.is_history = true;
			this.generateReport();
		});
	},
	mounted() {
		this.refreshTopHeight();
	}
}
</script>

